package com.happyrecyclingstation.handler;

import com.happyrecyclingstation.constant.MessageConstant;
import com.happyrecyclingstation.utils.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler
    public Result handlerException(Exception e){
        log.error("其他异常:{}", e.getMessage());
        return Result.error(e.getMessage());
    }

    @ExceptionHandler
    public Result handlerDuplicateKeyException(DuplicateKeyException e){
        log.error("重复条目", e.getMessage());
        String message = e.getMessage();
        String errMsg = message.substring(message.indexOf("Duplicate entry"));
        String[] s = errMsg.split(" ");
        return Result.error(s[2] + MessageConstant.ALREADY_EXIST);
    }
}
